<?php
class JournalBank extends AppModel {
    var $belongsTo = array(
        'Transaction'
    );
   
    function getTotal($month = null, $year = null, $balanceinquiry = false) {
        if ( is_null($month) ) {
            $month = date('m');
        }
        
        if ( is_null($year) ) {
            $year = date('Y');
        }
        
        $ret = array(
            'balance' => null, 'total_debit' => null,
            'total_credit' => null, 'year' => $year,
            'month' => $month
        );
        
        $conditions = array(
            $this->alias . '.transaction_date <' => $year . '-' .
                    $month . '-01'
        );
        
        if ( $balanceinquiry ) {
            $conditions = array(
                $this->alias . '.transaction_date <=' => date('Y-m-d') 
            );
        }
        
        $t = $this->find('all', array(
            'conditions' => $conditions,
            'fields' => array('debit_amount', 'credit_amount')
        ));
        
        foreach ($t as $k => $r) {
            $ret['total_credit'] += $r[$this->alias]['credit_amount'];
            $ret['total_debit']  += $r[$this->alias]['debit_amount'];
        }
        
        $ret['balance'] = $ret['total_debit'] - $ret['total_credit'];
        
        return $ret;
    }
}
?>
